package com.work.cos.web.controller.api;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.work.cos.domain.entity.SystemConfigEntity;
import com.work.cos.domain.entity.UserEntity;
import com.work.cos.domain.vo.ComServiceResVo;
import com.work.cos.service.interfc.ISendSMSService;
import com.work.cos.service.interfc.ISystemConfigService;
import com.work.cos.service.interfc.IUserService;
import com.work.cos.service.interfc.IVerCodeLogService;
import com.work.cos.util.ConfigInfo;
import com.work.cos.util.DateUtils;

/**
 * 
 * @author 注册登录
 *
 */
@RestController
@RequestMapping("/api")
public class LoginController {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private IUserService userService;
	@Autowired
	private ISendSMSService smsService;
	@Autowired
	private IVerCodeLogService verCodeLogService;
	@Autowired
	private ISystemConfigService systemConfigService;
	
	private String imgPath;

	/**
	 * 个人注册接口
	 * @param phone
	 * @param password
	 * @param verCode
     * @return
     */
	@PostMapping(value = "/register")
	public ComServiceResVo registerMobile(@RequestParam Long phone,@RequestParam String password,
			@RequestParam String verCode,@RequestParam(required = false) Long relationCode) {
		
		return userService.doRegister(phone, password, verCode, relationCode);
	}

	/**
	 * 个人登录接口
	 * @param phone
	 * @param password
     * @return
     */
	@PostMapping(value = "/login")
	public ComServiceResVo login(@RequestParam Long phone,
			@RequestParam String password,HttpServletRequest request) {
		return userService.doLogin(phone, password, request);
	}

	/**
	 * 获取验证码接口
	 * @param phone
	 * @return
     */
	@PostMapping(value = "/vercode")
	public ComServiceResVo registerVerCode(@RequestParam Long phone) {
		
		boolean flag = smsService.getMemberMobileIsExist(phone);
		if (flag) {
			
			LOGGER.info("mobile controller: register error...msg={}" , "已注册,无需重复注册!");
			return ComServiceResVo.returnErrorMessage("已注册,无需重复注册!");
		} else {
			
			boolean verCodeCheck = smsService.sendVerCodeByPhone(phone);
			if (verCodeCheck) {
				
				LOGGER.info("login controller get vercode success");
				return ComServiceResVo.returnSuccessStatus();
			} else {
				
				LOGGER.info("login controller: VerCode error...");
				return ComServiceResVo.returnErrorMessage("验证码获取失败!");
			}
		}
	}

	/**
	 * 个性头像上传
	 * @param request
	 * @param response
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@PostMapping(value = "/avator/upload")
	public ComServiceResVo avatorUpload(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
		
		LOGGER.info("login controller: avatorUpload in...msg={}" , request);
		
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			//取得request中的所有文件名  
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				//记录上传过程起始时的时间，用来计算上传时间  
				int pre = (int) System.currentTimeMillis();
				//取得上传文件  
				MultipartFile file = multiRequest.getFile(iter.next());
				SystemConfigEntity systemConfig = systemConfigService.getSystemConfigInfoByConfigKey(ConfigInfo.UPLOAD_USER_IMAGE_PATH);
				this.imgPath = getSystemImagePath();
				if (file != null) {
					//取得当前上传文件的文件名称  
					String myFileName = file.getOriginalFilename();
					//如果名称不为"",说明该文件存在，否则说明该文件不存在  
					if (myFileName.trim() != "") {
						//重命名上传后的文件名
						String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
						String fileName = "user_" + DateUtils.getDate2String(new Date()) + suffix;
						
						if (null != systemConfig) {
							//定义上传路径  
							String path = systemConfig.getConfigValue() + fileName;
							File localFile = new File(path);
							file.transferTo(localFile);
							
							Map<String,Object> map = new HashMap<>();
							map.put("avatorUrl", imgPath);
							map.put("fileName", fileName);
							
							LOGGER.info("login controller: avator upload success...time={}", (int) System.currentTimeMillis() - pre);
							return ComServiceResVo.returnEntity(map);
						} else {

							String message = "上传路径不存在!";
							LOGGER.info("login controller: avator upload error...msg={}", message);
							return ComServiceResVo.returnErrorMessage(message);
						}
					}
				} else {

					String message = "上传文件不存在!";
					LOGGER.info("login controller: avator upload error...msg={}", message);
					return ComServiceResVo.returnErrorMessage(message);
				}
				
			}
		}
		
		return ComServiceResVo.returnErrorMessage("更换异常，请重新上传");
	}

	/**
	 * 个性头像保存
	 * @param useId
	 * @param fileName
     * @return
     */
	@PostMapping(value = "/avator/save")
	public ComServiceResVo avatorSave(@RequestParam Long useId,@RequestParam String fileName) {
		
		LOGGER.info("mobile controller: avatorSave in...");
		
		boolean flag = userService.updateAvator(useId, fileName);
		if (flag) {

			LOGGER.info("mobile controller: avator save success...");
			return ComServiceResVo.returnSuccessStatus();
		} else {
			
			String message = "保存异常，请重新保存";
			LOGGER.info("mobile controller: avatorSave error...msg={}", message);
			return ComServiceResVo.returnErrorMessage(message);
		}

	}


	/**
	 * 验证码密码修改接口
	 * @param phone
	 * @param password
	 * @param verCode
     * @return
     */
	@PostMapping(value = "/edit/pwd")
	public ComServiceResVo EditPwd(@RequestParam Long phone,@RequestParam String password,
			@RequestParam String verCode) {
		
		String message = "";
		String verCodeDb = verCodeLogService.getVerCodeNow(phone);
		if (verCodeDb.equals(verCode)) {
			
			boolean flag = userService.updateUserPwd(phone, password);
			
			if (flag) {
				
				return ComServiceResVo.returnSuccessStatus();
			} else {

				message = "密码修改失败!";
				LOGGER.info("login controller: edit pwd error...msg={}", message);
				return ComServiceResVo.returnErrorMessage(message);
			}
		} else {

			message = "验证码不正确!";
			LOGGER.info("login controller: edit pwd error...msg={}" , message);
			return ComServiceResVo.returnErrorMessage(message);
		}
	}

	/**
	 * 新旧密码修改密码接口
	 * @param phone
	 * @param oldPassword
	 * @param newPassword
     * @return
     */
	@PostMapping(value = "/edit/pwd/old")
	public ComServiceResVo updatePwdByOld(@RequestParam Long phone,@RequestParam String oldPassword,
			@RequestParam String newPassword) {
			
			String msg = "";
			
			UserEntity userInfo = userService.findUsers(phone, "");
			if (null != userInfo) {
				if (userInfo.getPassword().equals(oldPassword)) {
					
					boolean flag = userService.updateUserPwd(phone, newPassword);
					if (flag) {
			
						LOGGER.info("login controller: update pwd old success...");
						return ComServiceResVo.returnSuccessStatus();
					} else {

						msg = "密码修改失败!";
						LOGGER.info("login controller: update pwd old error...msg={}", msg);
						return ComServiceResVo.returnErrorMessage(msg);
					}
				} else {

					msg = "旧密码输入错误!";
					LOGGER.info("login controller: update pwd old error...msg={}", msg);
					return ComServiceResVo.returnErrorMessage(msg);
				}
			} else {

				msg = "该账户已经不存在!";
				LOGGER.info("login controller: update pwd old error...msg={}" ,msg);
				return ComServiceResVo.returnErrorMessage(msg);
			}
	}
	
	/**
	 * 获取图片相对路径
	 * @return
	 */
	private String getSystemImagePath(){
		this.imgPath = this.systemConfigService.getSystemConfigByConfigKey(ConfigInfo.WEB_USER_IMAGE_PATH);
		return this.imgPath;
	}
	
	
}
